package format

import (
	"fmt"
	"print_service/etc"
	"print_service/ziface"
	"strings"
)

type HtmlFormat struct {
	Title      string
	Headers    [][]string
	SubHeaders []string
	Rows       [][]string
	FontSize   int
	PageSize   *etc.PaperSize
}

func NewHtmlFormat(title string, headers [][]string, subHeaders []string, fontSize int, pageSize etc.PaperSize) ziface.IFormat {
	return &HtmlFormat{
		Title:      title,
		Headers:    headers,
		SubHeaders: subHeaders,
		FontSize:   fontSize,
		PageSize:   &pageSize,
	}
}

func (t *HtmlFormat) AddRow(row []string) {
	t.Rows = append(t.Rows, row)
}

func (t *HtmlFormat) formatRow(columns []string, colWidths []int) string {
	var formattedCols []string
	for i, col := range columns {
		formattedCols = append(formattedCols, fmt.Sprintf("%-*s", colWidths[i], col))
	}
	return strings.Join(formattedCols, " | ")
}

func (t *HtmlFormat) Generate() {
	var result strings.Builder

	result.WriteString("<html><head><style>")
	result.WriteString(fmt.Sprintf("table { font-size: %dpx; width: 100%%; border-collapse: collapse; }", t.FontSize))
	result.WriteString(fmt.Sprintf("th, td { border: 1px solid black; padding: 8px; text-align: center; }"))
	result.WriteString(fmt.Sprintf("th { background-color: #f2f2f2; font-size: %dpx; }", t.FontSize))
	result.WriteString("</style></head><body>")

	result.WriteString(fmt.Sprintf("<h1 style='font-size:%dpx;'>%s</h1>", t.FontSize+4, t.Title))

	result.WriteString("<table><thead>")
	t.appendHTMLHeaders(&result)
}

func (t *HtmlFormat) appendHTMLHeaders(result *strings.Builder) {
	for _, headerRow := range t.Headers {
		result.WriteString("<tr>")
		for _, header := range headerRow {
			result.WriteString(fmt.Sprintf("<th>%s</th>", header))
		}
		result.WriteString("</tr>")
	}
}

func (t *HtmlFormat) calculateColumnWidths() []int {
	maxCols := 0
	for _, headerRow := range t.Headers {
		if len(headerRow) > maxCols {
			maxCols = len(headerRow)
		}
	}
	colWidths := make([]int, maxCols)
	for _, headerRow := range t.Headers {
		for i, header := range headerRow {
			if len(header) > colWidths[i] {
				colWidths[i] = len(header)
			}
		}
	}
	for _, row := range t.Rows {
		for i, col := range row {
			if len(col) > colWidths[i] {
				colWidths[i] = len(col)
			}
		}
	}
	return colWidths
}

var _ ziface.IFormat = (*HtmlFormat)(nil)
